package com.spic.system.service.impl;

import com.spic.common.core.exception.ServiceException;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.core.utils.bean.BeanUtils;
import com.spic.common.security.utils.cache.DeptCacheUtils;
import com.spic.common.security.utils.cache.UserCacheUtils;
import com.spic.system.api.domain.SysDept;
import com.spic.system.api.domain.SysUser;
import com.spic.system.api.dto.DeptDTO;
import com.spic.system.api.dto.UserDTO;
import com.spic.system.domain.HrUser;
import com.spic.system.domain.UserAll;
import com.spic.system.mapper.HrUserMapper;
import com.spic.system.mapper.SysUserMapper;
import com.spic.system.mapper.UserAllMapper;
import com.spic.system.service.IHrService;
import com.spic.system.service.ISysDeptService;
import com.spic.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author 290512
 * @create 2022-06-09 16:14
 */
@Service
public class HrServiceImpl implements IHrService
{
    @Autowired
    private HrUserMapper hrUserMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private UserAllMapper userAllMapper;

    /**
     * 查询hr_user
     *
     * @param personnelCode hr_user主键
     * @return hr_user
     */
    @Override
    public HrUser selectHrUserByPersonnelCode(String personnelCode)
    {
        return hrUserMapper.selectHrUserByPersonnelCode(personnelCode);
    }

    /**
     * 查询hr_user列表
     *
     * @param hrUser hr_user
     * @return hr_user
     */
    @Override
    public List<HrUser> selectHrUserList(HrUser hrUser)
    {
        return hrUserMapper.selectHrUserList(hrUser);
    }

    /**
     * 新增hr_user
     *
     * @param hrUser hr_user
     * @return 结果
     */
    @Override
    public int insertHrUser(HrUser hrUser)
    {
        return hrUserMapper.insertHrUser(hrUser);
    }

    /**
     * 修改hr_user
     *
     * @param hrUser hr_user
     * @return 结果
     */
    @Override
    public int updateHrUser(HrUser hrUser)
    {
        return hrUserMapper.updateHrUser(hrUser);
    }

    /**
     * 批量删除hr_user
     *
     * @param personnelCodes 需要删除的hr_user主键
     * @return 结果
     */
    @Override
    public int deleteHrUserByPersonnelCodes(String[] personnelCodes)
    {
        return hrUserMapper.deleteHrUserByPersonnelCodes(personnelCodes);
    }

    /**
     * 删除hr_user信息
     *
     * @param personnelCode hr_user主键
     * @return 结果
     */
    @Override
    public int deleteHrUserByPersonnelCode(String personnelCode)
    {
        return hrUserMapper.deleteHrUserByPersonnelCode(personnelCode);
    }

    @Override
    public String importData(List<HrUser> hrUserList)
    {
        if (StringUtils.isNull(hrUserList) || hrUserList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int updateNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for(HrUser hrUser:hrUserList ){
            if(StringUtils.isEmpty(hrUser.getPersonnelCode())){
                failureNum++;
                continue;
            }
            HrUser hr = hrUserMapper.selectHrUserByPersonnelCode(hrUser.getPersonnelCode());
            if(hr==null){
                hrUserMapper.insertHrUser(hrUser);
                successNum++;
            }else{
                hrUserMapper.updateHrUser(hrUser);
                updateNum++;
            }
        }
        successMsg.insert(0, "数据已导入成功！共新增 " + successNum + " 条,更新"+updateNum+"条,导入失败"+failureNum+"条, 数据如下：");
        return successMsg.toString() + failureMsg;
    }
    /**
     * 人员同步
     */
    @Override
    public void synchronizationHr()
    {
        List<HrUser> hrUsers = hrUserMapper.selectHrUserAllList();
        for (HrUser hrUser : hrUsers)
        {
            String erpDepartment = hrUser.getErpDepartment();
            int count = userMapper.checkUserNameUnique(hrUser.getPersonnelCode());
            if (count > 0)
            {
                Long deptId = 1386L; //未分配用户的部门id
                Long userId = null;
                String name = hrUser.getPersonnelCode();
                List<DeptDTO> list = DeptCacheUtils.getCache();
                List<UserDTO> cache = UserCacheUtils.getCache();
                List<DeptDTO> collect = list.stream().filter(f -> f.getParentId() == 100L).collect(Collectors.toList());
                for (DeptDTO deptDTO : collect)
                {
                    String deptName = deptDTO.getDeptName();
                    if(erpDepartment.equals(deptName)){
                        deptId = deptDTO.getDeptId();
                        break;
                    }
                }

                for (UserDTO userDTO : cache)
                {
                    String userName = userDTO.getUserName();
                    if(name.equals(userName)){
                        userId = userDTO.getUserId();
                        String dId = userDTO.getDeptId();
                        Long d = deptId;
                        List<DeptDTO> collect2 = list.stream().filter(f -> f.getParentId() == d && dId.equals(f.getDeptId()+"")).collect(Collectors.toList());
                        if(collect2!=null && collect2.size()>0){
                            deptId = Long.valueOf(userDTO.getDeptId());
                        }
                        break;
                    }
                }

                if(deptId!=1386L){
                    String deptName = erpDepartment+"未分配角色用户";
                    Long d = deptId;
                    List<DeptDTO> collect1 = list.stream().filter(f -> f.getParentId() == d && deptName.equals(f.getDeptName())).collect(Collectors.toList());
                    if(collect1!=null && collect1.size()>0){
                        deptId = collect1.get(0).getDeptId();
                    }else
                    {
                        List<DeptDTO> collect2 = collect.stream().filter(ff -> ff.getDeptId() == d).collect(Collectors.toList());
                        if(collect2!=null && collect2.size()>0){
                            SysDept sysDept = new SysDept();
                            sysDept.setParentId(deptId);
                            sysDept.setDeptName(deptName);
                            sysDept.setOrderNum("0");
                            sysDept.setStatus("0");
                            deptId = sysDeptService.insertDeptNoAuth(sysDept);
                        }

                    }
                }
                //存在更新
                SysUser user = new SysUser();
                user.setUserId(userId);
                user.setUpdateBy("admin");
                user.setUpdateTime(new Date());
                user.setDeptId(deptId);
                user.setNickName(hrUser.getName());
                user.setPhonenumber(hrUser.getPhoneNumber());
                userService.updateUser(user);
            }else{
                //部门
                Long deptId = 1386L; //未分配用户的部门id
                //判断部门是否存在 存在获取部门id
                List<DeptDTO> list = DeptCacheUtils.getCache();
                List<DeptDTO> collect = list.stream().filter(f -> f.getParentId() == 100L).collect(Collectors.toList());
                for (DeptDTO deptDTO : collect)
                {
                    String deptName = deptDTO.getDeptName();
                    if(erpDepartment.equals(deptName)){
                        deptId = deptDTO.getDeptId();
                        break;
                    }
                }
                //新增
                if(deptId!=1386L){
                    String deptName = erpDepartment+"未分配角色用户";
                    Long d = deptId;
                    List<DeptDTO> collect1 = list.stream().filter(f -> f.getParentId() == d && deptName.equals(f.getDeptName())).collect(Collectors.toList());
                    if(collect1!=null && collect1.size()>0){
                        deptId = collect1.get(0).getDeptId();
                    }else
                    {
                        SysDept sysDept = new SysDept();
                        sysDept.setParentId(deptId);
                        sysDept.setDeptName(deptName);
                        sysDept.setOrderNum("0");
                        sysDept.setStatus("0");
                        deptId = sysDeptService.insertDeptNoAuth(sysDept);
                    }
                }
                SysUser user = new SysUser();
                user.setCreateBy("admin");
                user.setCreateTime(new Date());
                user.setPassword(SecurityUtils.encryptPassword("Long189%"));
                user.setUserName(hrUser.getPersonnelCode());
                user.setDeptId(deptId);
                user.setNickName(hrUser.getName());
                user.setPhonenumber(hrUser.getPhoneNumber());
                user.setSex("男".equals(hrUser.getSex())?"0":"1");
                user.setStatus("0");
                userService.insertUser(user);
            }

        }

    }

    @Override
    public void syncHrUser2All() {
        List<HrUser> hrUsers = hrUserMapper.selectHrUserAllList();
        for (HrUser hrUser : hrUsers) {
            executor.execute(() -> {
                UserAll userAllParam = new UserAll();
                userAllParam.setPersonnelCode(hrUser.getPersonnelCode());
                List<UserAll> list = userAllMapper.selectUserAllList(userAllParam);
                UserAll userAll = new UserAll();
                BeanUtils.copyBeanProp(userAll, hrUser);
                userAll.setSource(1);
                if(list.size() == 0) {
                    userAllMapper.insertUserAll(userAll);
                } else {
                    userAllMapper.updateUserAll(userAll);
                }
            });
        }
    }
}
